package com.dbms.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SnowflakeIdGenerator {
    // 起始的时间戳，这里使用2024-01-01 00:00:00 UTC的时间戳作为起始值，可根据需要调整
    private static final long START_TIMESTAMP = 1704067200000L;

    // 机器ID所占的位数
    private static final long WORKER_ID_BITS = 5L;
    // 数据中心ID所占的位数
    private static final long DATA_CENTER_ID_BITS = 5L;
    // 序列号所占的位数
    private static final long SEQUENCE_BITS = 12L;

    // 机器ID的偏移量
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    // 数据中心ID的偏移量
    private static final long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    // 时间戳的偏移量
    private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS;

    // 最大的机器ID值
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    // 最大的数据中心ID值
    private static final long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BITS);
    // 最大的序列号值
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);

    // 机器ID
    private long workerId;
    // 数据中心ID
    private long dataCenterId;
    // 序列号
    private long sequence = 0L;
    // 上一次生成ID的时间戳
    private long lastTimestamp = -1L;

    public SnowflakeIdGenerator(@Value("${snowflake.worker-id}") long workerId,
                                 @Value("${snowflake.data-center-id}") long dataCenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("非法的机器ID：" + workerId);
        }
        if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
            throw new IllegalArgumentException("非法的数据中心ID：" + dataCenterId);
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
        System.out.println("初始化雪花算法生成器，机器ID：" + workerId + "，数据中心ID：" + dataCenterId);
    }

    // 获取下一个唯一ID
    public synchronized Long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("时钟倒退了，请检查系统时钟是否正确！");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT)
                | (dataCenterId << DATA_CENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence;
    }

    // 获取当前时间戳
    private long timeGen() {
        return System.currentTimeMillis();
    }

    // 等待直到下一个毫秒
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }
}
